//
//  MyAlertView.m
//  BaseLib
//
//  Created by CPX on 2018/6/14.
//  Copyright © 2018年 CPX. All rights reserved.
//

#import "MyAlertView.h"
#import "YYCategories.h"

/**
 基类弹框View
 @author yzl
 */
@interface MyAlertView()

@property (nonatomic,strong) NSMutableArray *btns;
@property (nonatomic,strong) UIView *whiteView;

@end

@implementation MyAlertView

- (void)initUI{
    [super initUI];
    
    self.whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth - 80, 191)];
    self.whiteView.backgroundColor = [UIColor whiteColor];
    self.whiteView.layer.masksToBounds = YES;
    self.whiteView.layer.cornerRadius = 5;
    self.whiteView.center = self.contentView.center;
    [self.contentView addSubview:self.whiteView];
    
    self.titleLable = [UILabel new];
    self.titleLable.font = [UIFont systemFontOfSize:16];
    self.titleLable.width = self.whiteView.width - 40;
    self.titleLable.numberOfLines = 0;
    self.titleLable.textColor = UIColorHex(#00000088);
    [self.whiteView addSubview:self.titleLable];
    
}

+ (instancetype)alertViewWithTitle:(NSString *)title block:(MyAlertBlock)block{
    MyAlertView *alert = [MyAlertView new];
    alert.removeOnTouchOutside = NO;
    alert.titleLable.text = title;
    alert.block = block;
    return alert;
}

- (void)addActionWithTitle:(NSString *)title color:(UIColor *)color{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:title forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    [btn addTarget:self action:@selector(onButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
    [btn setTitleColor:color forState:UIControlStateNormal];
    [self.whiteView addSubview:btn];
    [self.btns addObject:btn];
}

- (void)layoutSubviews{
    [super layoutSubviews];
    
    CGSize size = [self.titleLable sizeThatFits:CGSizeMake(self.titleLable.width, MAXFLOAT)];
    self.titleLable.height = size.height;
    self.titleLable.top = 20;
    
    self.titleLable.left = 20;
    
    self.whiteView.height = self.titleLable.bottom + 30 + 36+8;
    self.whiteView.center = self.contentView.center;
    
    CGFloat right = self.titleLable.superview.width - 8;
    CGFloat bottom = self.titleLable.superview.height - 8;
    for (NSInteger i = self.btns.count -1; i>=0; i--) {
        UIButton *btn = self.btns[i];
        btn.size = CGSizeMake(75, 36);
        btn.right = right;
        btn.bottom = bottom;
        right -= 75;
    }
}

- (NSMutableArray*)btns{
    if (!_btns) {
        _btns = [NSMutableArray array];
    }
    return _btns;
}

- (void)onButtonTouched:(UIButton*)sender{
    NSInteger idx = [self.btns indexOfObject:sender];
    if (self.block) {
        self.block(idx);
    }
    [self removeFromSuperview];
}

@end
